<?php
namespace app\web\admin;

use app\common\builder\ZBuilder;
use app\web\model\Platform;
use app\web\model\Shop as myModel;
use app\web\model\ShopImages;
use app\web\model\Reason;
use app\web\model\Technician;
use app\web\model\User;
use app\web\model\ShopBalance;
use app\web\model\Config;
use app\lib\model\Price;
use Yansongda\Pay\Pay;
use think\Db;

/**
 * 店铺
 * @package
 */
class Shop extends Base 
{
    public $check_status = ['未审核','已审核','未通过'];
    public $balance_type = ['取消订单','订单结算','加项补差','提现','平台调整'];
	public function index($group = 'tab1')
	{
        $list_tab = [
            'tab1' => ['title' => '店铺列表', 'url' => url('index', ['group' => 'tab1']),'count'=>myModel::where(['is_sub'=>1,'check_status'=>0])->count()],
            'tab2' => ['title' => '店铺相册列表', 'url' => url('index', ['group' => 'tab2']),'count'=>ShopImages::where('status',0)->count()],
        ];
		$map = $this->getMap();
        if($group == 'tab1'){
            $map[] = ['a.is_sub','=',1];
            $map[] = ['a.p_id','=',0];
            $data_list = myModel::alias('a')->where($map)
                        ->field('a.id,a.shop_name,a.enterprise_name,a.city,a.license_no,a.personal_wechat,a.balance,a.shop_mobile,a.business_start,a.business_end,a.check_status,concat(a.province,a.city,a.area,a.address) as shop_address,a.t_number,a.deal_number,a.praise_rate,a.refund_rate,a.period,a.period_time')
                        ->group('a.id')
                        ->order($this->getOrder('a.create_time desc'))
                        ->paginate();
            $addColumns = [
                ['shop_name','店铺名称'],
                ['enterprise_name','企业名称'],
                ['license_no','营业执照编号'],
                ['city','城市'],
                ['shop_address','店铺地址'],
                ['personal_wechat','微信号'],
                ['shop_mobile', '商户电话'],
                ['business_start', '营业开始时间'],
                ['business_end', '营业结束时间'],
                ['balance','余额'],
                ['deal_number','成交单数'],
                ['t_number','技师数量'],
                ['praise_rate','好评率(%)'],
                ['refund_rate','退款率(%)'],
                ['period_time','合作期限'],
                ['check_status','状态','status','',$this->check_status],
                ['right_button', '操作', 'btn']
            ];
            return ZBuilder::make('table')
                ->setTableName('shop')
                ->hideCheckBox($addColumns)
                ->setTabNav($list_tab,'tab1')
                ->addColumns($addColumns)
                ->setRowList($data_list)
                ->addOrder('t_number,praise_rate,refund_rate,deal_number,period_time')
                ->setColumnWidth('shop_mobile',120)
                ->setSearch(['shop_name'=>'店铺名称','shop_mobile'=>'商户电话','city'=>'城市'])
                ->addFilterList('check_status',$this->check_status)
                ->addRightButtons([
                    'edit'=>['title'=>'编辑'],
                    'check'=>['title'=>'审核','href'=>url('check',['id'=>'__id__'])],
                    'editbalance' => ['title'=>'余额调整','href'=>url('editbalance',['id'=>'__id__'])]
                ])
                // ->replaceRightButton(['check_status' => ['in','1,2']], '','check') // 修改id为1的按钮
                ->addTopButtons([
                    'myexport' => ['title'=>'导出','class'=>'btn btn-primary ajax-post myexport-btn','href'=>'javascript:void(0);'],
                ])
                ->replaceRightButton(['check_status' => ['in','0,2']], '','editbalance') // 修改id为1的按钮
                // ->addTrClass('check_status0', 'check_status', '=', 0)
                ->setExtraCss($this->getCss())
                ->js("printer")
                ->fetch();
        }else{
            $data_list = ShopImages::alias('a')
                                    ->leftjoin('shop b','b.id=a.shop_id')
                                    ->field('a.*,b.shop_name,b.shop_mobile')
                                    ->where($map)
                                    ->order('create_time desc')
                                    ->paginate()->each(function($i,$k){
                                        return $this->tableImg($i,$k,'image');
                                    });
            $addColumns = [
                ['shop_name','店铺名称'],
                ['shop_mobile','店铺电话'],
                ['image','店铺相册'],
                ['status','状态','status','',$this->check_status],
                ['right_button', '操作', 'btn']
            ];
            return ZBuilder::make('table')
                ->setTableName('shop_images')
                ->hideCheckBox($addColumns)
                ->setTabNav($list_tab,'tab2')
                ->addColumns($addColumns)
                ->setRowList($data_list)
                ->setColumnWidth('shop_mobile',120)
                ->setSearch(['shop_name'=>'店铺名称','shop_mobile'=>'商户电话'])
                ->addFilterList('status',['待审核','通过','未通过'])
                ->addRightButtons(['checkImage'=>['title'=>'审核','href'=>url('checkImage',['id'=>'__id__'])]])
                // ->replaceRightButton(['status' => ['in','1,2']], '','checkImage') // 修改id为1的按钮
                // ->addTrClass('check_status0', 'status', '=', 0)
                ->setExtraCss($this->getCss())
                ->fetch();
        } 
	}
    public function editbalance($id)
    {
        $info = myModel::get($id);
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if(!$data['notes']) $this->error('调整余额备注不能为空');
            $change_balance = Price::pricecalc($data['balance1'],'-',$info['balance']);
            Db::startTrans();
            $res = ShopBalance::change($data['id'],$change_balance,4,$data['notes']);
            if($res){
                Db::commit();
                $this->success('操作成功','index?group=tab1');
            }
            Db::rollback();
            $this->error('操作失败');
        }
        return ZBuilder::make('form')
            ->addFormItems([
                ['hidden','id'],
                ['static','balance','商家余额'],
                ['number','balance1','调整后余额'],
                ['text','notes','备注']
            ])
            ->setFormData($info)
            ->fetch();
    }
    /**
     * 导出
     * [myexport description]
     * @return [type] [description]
     */
    public function myexport()
    {  
        $map = $this->getMap();
        $map[] = ['is_sub','=',1];
        $shop_list = myModel::where($map)
                    ->order($this->getOrder('id desc'))
                    ->select()->each(function($item,$k){
                        $item['is_legal'] = ['否','是'][$item['is_legal']];
                        // $item['period_time'] = $item['period_time'] == 0 ? '无限期' : date('Y-m-d',$item['period_time']);
                        $item['receiving_order_type'] = ['商家接单就默认技师接单成功','技师接单就默认接单成功','商家和技师都必须接单'][$item['receiving_order_type']];
                    });

        $cellName = [
            ['id','10','ID'],
            ['shop_name','18','店铺名称'],
            ['enterprise_name', '20', '企业名称'],
            ['license_no','18','营业执照编号'],
            ['shop_mobile','15','商务电话'],
            ['personal_wechat','15','个人微信号'],
            ['business_start','15','开始营业时间'],
            ['business_end','15','营业结束时间'],
            ['province','10','省份'],
            ['city','10','城市'],
            ['area','15','区县'],
            ['address','35','详细地址'],
            ['is_legal','10','法人和申请人是否同一人'],
            ['legal_name','15','法人姓名'],
            ['legal_idcard','20','法人身份证'],
            ['legal_mobile','18','法人电话'],
            ['person_name','20','申请人姓名'],
            ['technician_recommend','20','技师推荐数量'],
            ['project_recommend','20','项目推荐数量'],
            ['receiving_order_type','35','接单形式'],
            ['deal_number','18','成交单数'],
            ['praise_rate','18','好评率(%)'],
            ['t_number','18','技师数量'],
            ['refund_rate','18','退款率(%)'],
            ['period_time','20','合作到期时间'],
        ];
        plugin_action('Excel/Excel/export', ['pending_order', $cellName, $shop_list]);
    }

	public function checkimage($id)
    {
        $info = ShopImages::get($id);
        $reason = Reason::getSelectAll('status=1','reason');
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if($data['status'] == 2){
                if(!$data['reason']) $this->error('请选择不予通过原因');
                $data['reason'] = $reason[$data['reason']];
            }
            $data['check_time'] = $this->request->time();
            $data['check_uid'] = UID;
            $data['update_time'] = $this->request->time();
            if (ShopImages::where('id',$data['id'])->update($data)) {
                $this->success('操作成功','index?group=tab2');
            } else {
                $this->error('操作失败');
            }
        }
        $addFormItems = [
            ['hidden','id'],
            ['radio', 'status', '店铺审核状态', '', ['未审核','通过','不予通过'], 0],
            ['select','reason','不予通过原因','',$reason]
        ];
        return ZBuilder::make('form')
            ->addFormItems($addFormItems)
            ->setTrigger('status','2','reason')
            ->setFormData($info)
            ->fetch();
    }
    public function  check($id){
        $info = myModel::get($id);
        $reason = Reason::getSelectAll('status=1','reason');
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if($data['check_status'] == 2){
                if(!$data['check_reason']) $this->error('请选择不予通过原因');
                $data['check_reason'] = $reason[$data['check_reason']];
            }
            if($data['check_status'] == 1){
                if(empty($data['technician_recommend']) || $data['technician_recommend'] < 1) $this->error('技师推荐数量必须是正整数');
                if(empty($data['project_recommend']) || $data['project_recommend'] < 1) $this->error('项目推荐数量须是正整数');
                if(!isset($data['receiving_order_type'])) $this->error('请选择接单形式');
                if($data['period'] < 0) $this->error('合作期限不能是负数');
                $data['period'] = (int)$data['period'];
                $data['period_time'] = $data['period'] == 0 ? 0 : time() + 86400*$data['period'];
                $data['is_period'] = $data['period_time'] > 0 && $data['period_time'] < time() ? 1 : 0;
                Technician::where('shop_id',$id)->update(['period_time'=>$data['period_time'],'is_period'=>$data['is_period'],'period'=>$data['period']]);
            }
            $data['check_time'] = $this->request->time();
            $data['check_uid'] = UID;
            $data['update_time'] = $this->request->time();
            if (myModel::where('id',$data['id'])->update($data)) {
                if($data['check_status'] == 1){  //审核通过
                    $user = User::get($info['user_id']);
                    $user->shop_id = $info['id'];
                    $user->save();
                }elseif($data['check_status'] == 2){
                    User::where('id',$info['user_id'])->update(['shop_id'=>0]);
                }
                $this->success('操作成功','index');
            } else {
                $this->error('操作失败');
            }
        }
        $addFormItems = [
            ['hidden','id'],
            ['radio', 'check_status', '店铺审核状态', '', ['未审核','通过','不予通过'], 0],
            ['select','check_reason','不予通过原因','',$reason],
            ['number','period','合作期限','自审核通过后N天到期0表示无限期'],
            ['number','technician_recommend','技师推荐数量','必填',10],
            ['number','project_recommend','项目推荐数量','必填',10],
            ['select','receiving_order_type','接单形式','必填',['商家接单就默认技师接单成功','技师接单就默认接单成功','商家和技师都必须接单'],0],
        ];
        return ZBuilder::make('form')
            ->addFormItems($addFormItems)
            ->setTrigger('check_status','2','check_reason')
            ->setTrigger('check_status','1','period,technician_recommend,project_recommend,receiving_order_type')
            ->setFormData($info)
            ->fetch();
    }
	public function edit($id = null){
		if ($id === null) {
			$this->error('缺少参数');
		}
		$info = myModel::find($id);
        if($this->request->isPost()){
            $data = $this->request->post();
            $data['period_time'] = $data['period'] == 0 ? 0 : $info->check_time + 86400*$data['period'];
            $data['is_period'] = $data['period_time'] > 0 && $data['period_time'] < time() ? 1 : 0;
            Technician::where('shop_id',$id)->update(['period_time'=>$data['period_time'],'is_period'=>$data['is_period'],'period'=>$data['period']]);
            $res = $info->save($data);
            if($res) $this->success('操作成功','index');
            $this->error('操作失败');
        }
        $info['address'] = $info['province'].$info['city'].$info['area'].$info['address'];
        $info['is_legal1'] = ['否','是'][$info['is_legal']];
        $info['check_status1'] = $this->check_status[$info['check_status']];
    
		#获取数据，渲染模板
		return ZBuilder::make('form')
			->addFormItems([
                ['hidden','is_legal'],
                ['static:6','shop_name','店铺名称'],
                ['static:6','shop_mobile','商户电话'],
                ['static:6','check_status1','审核状态'],
                ['static:6','balance','余额'],
                ['static:6','enterprise_name','企业名称'],
                ['static:6','license_no','营业执照编号'],
                ['static:6','business_start','营业开始时间'],
                ['static:6','business_end','营业结束时间'],
                // ['static:6','wx_code','商务微信号'],
                ['static:6','personal_wechat','个人微信号'],
                ['static:6','address','店铺地址'],
                ['number','period','合作期限('.$info->period_time.')','自审核通过后N天到期0表示无限期'],
                ['number','technician_recommend','可推荐技师数量'],
                ['number','project_recommend','可推荐项目数量'],
                ['select','receiving_order_type','接单形式','必填',['商家接单就默认技师接单成功','技师接单就默认接单成功','商家和技师都必须接单'],0],
                
                ['gallery','promise_path','承诺函'],
                ['static:6','is_legal1','申请人和法人是否同一人'],
                ['static:6','legal_name','法人姓名'],
                ['static:6','legal_idcard','法人身份证'],
                ['static:6','legal_mobile','法人电话'],
                ['static:6','person_name','申请人姓名'],
                ['gallery','legal_just','法人身份正面照'],
                ['gallery','legal_back','法人身份反面照'],
                ['gallery','hold_legal_just','法人手持身份正面照'],
                ['gallery','hold_legal_back','法人手持身份反面照'],
                ['gallery','person_just','申请人身份正面照'],
                ['gallery','person_back','申请人身份反面照'],
                ['gallery','hold_person_just','申请人手持身份正面照'],
                ['gallery','hold_person_back','申请人手持身份反面照'],
            ])
			->setFormData($info)
            // ->hideBtn('submit')
            ->setTrigger('is_legal','1','hold_legal_just,hold_legal_back')
            ->setTrigger('is_legal','0','legal_mobile,person_name,person_just,person_back,hold_person_just,hold_person_back')
			->fetch();
	}

	public function withdrawal()
    {
        $map = $this->getMap();
        $map[] = ['a.balance_type','=',3];
        $list = ShopBalance::alias('a')
                        ->leftjoin('shop b','b.id=a.shop_id')
                        ->field('a.id,abs(a.change_balance) as change_balance,a.status,b.shop_name,b.shop_mobile,a.create_time')
                        ->where($map)
                        ->order($this->getOrder('a.id desc'))
                        ->paginate();
        return ZBuilder::make('table')
            ->hideCheckbox()
            ->setTableName('shop_balance')
            ->setSearch(['shop_name' => '店铺名称','shop_mobile'=>'店铺电话']) // 设置搜索参数
            ->addColumns([
                ['shop_name','店铺名称'],
                ['shop_mobile','店铺电话'],
                ['change_balance','提现金额'],
                ['status','审核状态','status','',['未审核','已通过','未通过']],
                ['create_time','提交时间'],
                ['right_button', '操作', 'btn']
            ])
            ->addOrder('change_balance,create_time')
            ->addFilterList('status',['未审核','已通过','未通过'])
            ->addRightButtons(['checkwithdrawal'=>['title'=>'审核','href'=>url('checkwithdrawal',['id'=>'__id__'])]])
            ->replaceRightButton(['status' => ['in','1,2']], '','checkwithdrawal') // 修改id为1的按钮
            ->setRowList($list)
            ->fetch();
    }


    /**
     * 商家提现
     * [checkwithdrawal description]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function checkwithdrawal($id)
    {
        if($this->request->isPost()){
            $data = $this->request->post();
            $info = ShopBalance::get($data['id']);
            if($data['status'] == 0) $this->success('操作成功' ,'withdrawal');
            if($data['status'] == 2){
                $res = $info->save($data);
                if(!$res) $this->error('操作失败');
                $this->success('操作成功','withdrawal');
            }
            if($data['status'] == 1){
                $user = myModel::get($info['shop_id']);

                $order = [
                    'partner_trade_no' => $this->getOrderNo(),              //商户订单号
                    'openid' => $user['openid'],                        //收款人的openid
                    'check_name' => 'NO_CHECK',            //NO_CHECK：不校验真实姓名\FORCE_CHECK：强校验真实姓名
                    // 're_user_name'=>'张三',              //check_name为 FORCE_CHECK 校验实名的时候必须提交
                    'amount' => Price::priceyuantofen(-$info['change_balance']),                       //企业付款金额，单位为分
                    'desc' => '帐户提现',                  //付款说明
                    'type' => 'miniapp'
                ];

                try{
                    $res = Pay::wechat(Config::getWechatConfig(1))->transfer($order);
                } catch (\Exception $e) {
                    $this->error("支付接口异常".$e->getMessage());
                } 
          
                if($res['return_code'] == 'SUCCESS'){
                    $data['before_balance'] = $user['balance'];
                    $af_balanc = Price::pricecalc($user['balance'],'+',$info['change_balance']);
                    $data['after_balance'] = $af_balanc;
                    $user->balance = $af_balanc;
                    $user->save();
                    $info->save($data);
                    Platform::change([
                        'role' => 2,
                        'p_id' => $user['id'],
                        'platform_type' => 6,
                        'mobile' => $user['shop_mobile'],
                        'user_name' => $user['shop_name'],
                        'change_balance' => $info['change_balance'],
                        'notes' => '商家提现到零钱'
                    ]);
                    $this->success('提现成功','withdrawal');
                }
                $this->error('提现失败');
            }
        }
        $info = ShopBalance::field('id,abs(change_balance) as change_balance,shop_id,status')->get($id);
        $info->tot_withdrawal = ShopBalance::where(['shop_id'=>$info->shop_id,'balance_type'=>3,'status'=>1])->sum('change_balance');
        $info->tot_withdrawal = abs($info->tot_withdrawal);
        $info->withdrawal_balance = MyModel::where('id',$info->shop_id)->value('balance');
        $list = ShopBalance::where(['shop_id'=>$info->shop_id,'balance_type'=>3,'status'=>1])
                            ->field('id,shop_id,abs(change_balance) as change_balance,create_time')
                            ->select()
                            ->toArray();
        $info['order_goods'] = $list;
        $content = "";
        foreach ($list as $key => $v) {
            $content .= "<tr>
                            <td>{$v['change_balance']}</td>
                            <td>{$v['create_time']}</td>
                        </tr>";
        }
        $html = <<<EOF
<div  id="product-table" style="display:none">
    <table class="table table-builder table-hover table-bordered table-striped ">
        <tr>
            <th>提现金额</th>
            <th>提现时间</th>
        </tr>
        {$content}
    </table>
</div>
<script>
    $(function(){
        $("#form_group_goods .form-control-static").html($("#product-table").html());

    })
</script>
EOF;
        return ZBuilder::make('form')
            ->setPageTips('审核通过后提现金额直接到账微信')
            ->addFormItems([
                ['hidden','id'],
                ['static','withdrawal_balance','该商家可提现余额(元)'],
                ['static','tot_withdrawal','该商家总共提现金额(元)'],
                ['static', 'change_balance','提现金额'],
                ['radio', 'status', '状态', '', ['未审核','已通过','未通过'], 1],
            ])
            ->addStatic('goods', '提现记录')
            ->setExtraHtml($html)
            ->setFormData($info)
            ->fetch();
    }



    public function balance()
    {
        $map = $this->getMap();
        $map[] = ['a.status','=',1];
        foreach ($map as $key => $value) {
            if($value[0] == 'update_time') $map[$key][0] = 'a.update_time';
        }
        $list = ShopBalance::alias('a')
                        ->leftjoin('shop b','b.id=a.shop_id')
                        ->field('a.id,a.balance_type,b.city,a.before_balance,a.after_balance,a.change_balance,a.notes,a.status,b.shop_name,b.shop_mobile,a.update_time')
                        ->where($map)
                        ->order($this->getOrder('a.update_time desc'))
                        ->paginate();
        return ZBuilder::make('table')
            ->hideCheckbox()
            ->setTableName('technician_balance')
            ->setSearch(['shop_name' => '店铺名称','shop_mobile'=>'店铺电话','city'=>'城市']) // 设置搜索参数
            ->addColumns([
                ['shop_name','店铺名称'],
                ['shop_mobile','店铺电话'],
                ['city','所在城市'],
                ['balance_type','变动类型','status','',$this->balance_type],
                ['before_balance','变动前金额'],
                ['change_balance','变动金额'],
                ['after_balance','变动后金额'],
                ['notes','备注'],
                ['update_time','变动时间'],
            ])
            ->addTimeFilter('update_time','','变动时间')
            ->addFilterList('balance_type',$this->balance_type)
            ->addOrder('change_balance,update_time')
            ->setRowList($list)
            ->fetch();
    }

}